package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.StrategyContent;
import cn.wolfcode.trip.base.domain.StrategyDetail;
import cn.wolfcode.trip.base.mapper.StrategyContentMapper;
import cn.wolfcode.trip.base.mapper.StrategyDetailMapper;
import cn.wolfcode.trip.base.query.StrategyDetailQuery;
import cn.wolfcode.trip.base.service.IStrategyDetailService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by 13925 on 2018/11/4.
 */
@Service
public class StrategyDetailServiceImpl implements IStrategyDetailService {
    @Autowired
    private StrategyDetailMapper strategyDetailMapper;

    @Autowired
    private StrategyContentMapper strategyContentMapper;

    @Override
    public PageInfo query(StrategyDetailQuery qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());
        List<StrategyDetail> list = strategyDetailMapper.selectForList(qo);
        return new PageInfo(list);
    }

    public void saveOrUpdate(StrategyDetail strategyDetail) {
        //如果是发布状态 则设置发布时间
        if (strategyDetail.getState() == strategyDetail.STATE_RELEASE) {
            strategyDetail.setReleaseTime(new Date());
        }
        //序列号自动增长
        if (strategyDetail.getSequence() == null) {
            int sequence = strategyDetailMapper.selectAutoSequence(strategyDetail.getCatalog().getId());
            strategyDetail.setSequence(sequence);
        }
        //添加和编辑
        if (strategyDetail.getId() != null) {
            //修改攻略文章
            strategyDetailMapper.updateByPrimaryKey(strategyDetail);
            //修改攻略文章内容
            StrategyContent strategyContent = strategyDetail.getStrategyContent();
            strategyContent.setId(strategyDetail.getId());
            strategyContentMapper.updateByPrimaryKey(strategyContent);
        } else {
            strategyDetail.setReleaseTime(new Date());
            //添加攻略文章
            strategyDetailMapper.insert(strategyDetail);
            //添加攻略文章内容
            StrategyContent strategyContent = strategyDetail.getStrategyContent();
            strategyContent.setId(strategyDetail.getId());
            strategyContentMapper.insert(strategyContent);
        }
    }

    @Override
    public StrategyContent getContentByDetailId(Long detailId) {
        return strategyContentMapper.selectByPrimaryKey(detailId);
    }

    @Override
    public StrategyDetail get(Long id) {
        return strategyDetailMapper.selectByPrimaryKey(id);
    }
}
